package com.spice.im.group;

import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;


import com.spice.im.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SortAdapter2 extends ArrayAdapter<SortModel2> implements SectionIndexer{
	private List<SortModel2> list = null;
	
	private Context mContext;
	private ImageLoader mLoader;
	private List<String> checkMaps=new ArrayList<String>();
	private List<String> checkMapsName=new ArrayList<String>();
	private List<String> checkMapsUrl=new ArrayList<String>();
	private CheckBoxAndLinearListener listener;
	private int count=0;
	private List<SortModel2> copyConversationList;
	private ConversationFilter conversationFilter;
	private boolean notiyfyByFilter;
	List<String> memberItems;
	public SortAdapter2(Context mContext, List<SortModel2> list,CheckBoxAndLinearListener listener) {
		super(mContext, 0, list);
		this.mContext = mContext;
		this.list = list;
		mLoader=ImageLoader.getInstance();
		copyConversationList = new ArrayList<SortModel2>();
        copyConversationList.addAll(list);
		this.listener=listener;
	}

	public void updateListView(List<String> list){
		this.memberItems = list;
	}
	
	@Override
    public Filter getFilter() {
        if (conversationFilter == null) {
            conversationFilter = new ConversationFilter(list);
        }
        return conversationFilter;
    }

	public int getCount() {
		return this.list.size();
	}

//	public Object getItem(int position) {
//		return list.get(position);
//	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View view, ViewGroup parent) {
		final ViewHolder viewHolder;
		if (view == null) {
			viewHolder = new ViewHolder();
			view = LayoutInflater.from(mContext).inflate(R.layout.item_batch_friend, parent, false);
			viewHolder.fullLinear=(LinearLayout)view.findViewById(R.id.batch_friend_item_linear);
			viewHolder.friendLetter = (TextView) view.findViewById(R.id.letter);
			viewHolder.friendLine = (View) view.findViewById(R.id.catalog);
			viewHolder.friendName=(TextView)view.findViewById(R.id.friend_name);
			viewHolder.friendAvatar=(ImageView)view.findViewById(R.id.friend_avatar);
			viewHolder.check=(CheckBox)view.findViewById(R.id.batch_item_check);
			viewHolder.transferAmount=(TextView)view.findViewById(R.id.batch_item_transfer_money);
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) view.getTag();
		}
		
		int section = getSectionForPosition(position);
		
		if(position == getPositionForSection(section)){
			viewHolder.friendLetter.setVisibility(View.VISIBLE);
			viewHolder.friendLine.setVisibility(View.GONE);
		}else{
			viewHolder.friendLetter.setVisibility(View.GONE);
			viewHolder.friendLine.setVisibility(View.VISIBLE);
		}
		if (checkMaps.contains(this.list.get(position).getUid())) {
			viewHolder.check.setChecked(true);
		} else {
			viewHolder.check.setChecked(false);
		}
		if (memberItems != null && memberItems.contains(this.list.get(position).getUid())) {
			viewHolder.check.setVisibility(View.GONE);
		} else {
			viewHolder.check.setVisibility(View.VISIBLE);
		}
		
		viewHolder.friendName.setText(this.list.get(position).getName());
		viewHolder.friendLetter.setText(this.list.get(position).getSortLetters());
		mLoader.displayImage(this.list.get(position).getImgUrl(), viewHolder.friendAvatar, Options.getOptions(UIUtils.dip2px(mContext, ConstantConfig.AVATAR_RADIUS)));
		if(!TextUtils.isEmpty(list.get(position).getMoney())){
			viewHolder.transferAmount.setText("转账");
			String money = list.get(position).getMoney()+"元";
			
			SpannableString moneySpan = new SpannableString(money);
			ForegroundColorSpan colorSpan = new ForegroundColorSpan(mContext
					.getResources().getColor(R.color.batch_friend_transfer_amount));
			moneySpan.setSpan(colorSpan, 0, money.length(),
					Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

			viewHolder.transferAmount.append(moneySpan);
			viewHolder.transferAmount.setVisibility(View.VISIBLE);
		}else{
			viewHolder.transferAmount.setVisibility(View.GONE);
		}
		viewHolder.fullLinear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				listener.onLinearClicked(position);
			}
		});
//		viewHolder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//			
//			@Override
//			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//				// TODO Auto-generated method stub
//				if(isChecked)
//					count++;
//				else
//					count--;
//				checkMaps.put(position, isChecked);
//				listener.onChecked(count);
//			}
//		});
		viewHolder.check.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(viewHolder.check.isChecked())
				{
					checkMaps.add(list.get(position).getUid());
					checkMapsName.add(list.get(position).getName());
					checkMapsUrl.add(list.get(position).getImgUrl());
					count++;}
				else{
					checkMaps.remove(list.get(position).getUid());
					checkMapsName.remove(list.get(position).getName());
					checkMapsUrl.remove(list.get(position).getImgUrl());
					count--;}
				listener.onChecked(count);
			}
		});
		
		return view;

	}
	


	final static class ViewHolder {
		TextView friendLetter;
		CheckBox check;
		View friendLine;
		TextView friendName;
		ImageView friendAvatar;
		TextView transferAmount;
		LinearLayout fullLinear;
	}
	
	public List<String> getCheckMaps(){
		return checkMaps;
	}
	
	public List<String> getCheckMapsName(){
		return checkMapsName;
	}
	
	public List<String> getCheckMapsUrl(){
		return checkMapsUrl;
	}

	public int getSectionForPosition(int position) {
		return list.get(position).getSortLetters().charAt(0);
	}

	public int getPositionForSection(int section) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = list.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}
		
		return -1;
	}
	
	private String getAlpha(String str) {
		String  sortStr = str.trim().substring(0, 1).toUpperCase();
		if (sortStr.matches("[A-Z]")) {
			return sortStr;
		} else {
			return "#";
		}
	}

	@Override
	public Object[] getSections() {
		return null;
	}
	
	private class ConversationFilter extends Filter {
        List<SortModel2> mOriginalValues = null;

        public ConversationFilter(List<SortModel2> mList) {
            mOriginalValues = mList;
        }

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();

            if (mOriginalValues == null) {
                mOriginalValues = new ArrayList<SortModel2>();
            }
            if (prefix == null || prefix.length() == 0) {
                results.values = copyConversationList;
                results.count = copyConversationList.size();
            } else {
                String prefixString = prefix.toString();
                final int count = mOriginalValues.size();
                final ArrayList<SortModel2> newValues = new ArrayList<SortModel2>();

                for (int i = 0; i < count; i++) {
                    final SortModel2 value = mOriginalValues.get(i);
                    String username = value.getName();

                    // First match against the whole ,non-splitted value
                    if (username.startsWith(prefixString)) {
                        newValues.add(value);
                    } else{
                          final String[] words = username.split(" ");
                            final int wordCount = words.length;

                            // Start at index 0, in case valueText starts with space(s)
                            for (int k = 0; k < wordCount; k++) {
                                if (words[k].startsWith(prefixString)) {
                                    newValues.add(value);
                                    break;
                                }
                            }
                    }
                }

                results.values = newValues;
                results.count = newValues.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            list.clear();
            list.addAll((List<SortModel2>) results.values);
            if (results.count > 0) {
                notiyfyByFilter = true;
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }

        }

    }
	
	@Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        if(!notiyfyByFilter){
            copyConversationList.clear();
            copyConversationList.addAll(list);
            notiyfyByFilter = false;
        }
    }
	
    public interface CheckBoxAndLinearListener
    {
        void onChecked(int count);

        void onLinearClicked(int position);
    }
}